package com.ruoyi.generateTest.utils;

import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.utils.Constants;
import com.ruoyi.generateTest.domain.*;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * 生成题目工具类
 *
 * @author
 * @date
 */
public class GenerateQuestionsUtil {

    //写入的路径
    private final static String wordFilePath = "F:\\study\\项目\\考试系统\\word\\document_" + System.currentTimeMillis() + ".docx";
    private final static String wordFilePathLinx = "\\home\\exam\\word\\";
    private final static String wordFilePath1 = "F:\\study\\项目\\考试系统\\word\\document_";


    /**
     * 调用这个函数
     *
     * @param file                要生成题目的文档
     * @param singleQuestionNum   单选题数量
     * @param MultipleQuestionNum 多选题数量
     * @param shortQuestNum       简答题数量
     * @param difficulty          难度：0简单1中等2困难
     * @param paperNum            试卷套数
     * @return
     * @throws Exception
     */
    public static String SingleTalks(File file,String name, int singleQuestionNum, int MultipleQuestionNum, int shortQuestNum, int fillBlankNum, int torFNum,  int difficulty, int paperNum) throws Exception {
        Constants.apiKey = "sk-147806426fcc416f9aaba401c935c35d";
        //1.读取文件
//        File file = new File("F:\\study\\项目\\考试系统\\焊接检验.docx");
        FileInputStream fis = new FileInputStream(file);
        XWPFDocument document = new XWPFDocument(fis);
        List<XWPFParagraph> paragraphs = document.getParagraphs();
        StringBuilder text = new StringBuilder();
        for (XWPFParagraph paragraph : paragraphs) {
            text.append(paragraph.getText()).append("\n");
        }
        fis.close();

        int caseNum = 0;
        //2.生成
        List<String> promptList = convertList(singleQuestionNum, MultipleQuestionNum, shortQuestNum, fillBlankNum, torFNum, caseNum, difficulty, paperNum, text.toString());
        List singleChoicesQuestions=new ArrayList<>();
        List multipleChoicesQuestions=new ArrayList<>();
        List shortAnswerQuestions=new ArrayList<>();
        List fillBlankQuestions=new ArrayList<>();
        List torFQuestions=new ArrayList<>();
        List caseQuestions=new ArrayList<>();

        //多轮输入给模型
        //限制在promptList.size()次
        for (int i = 0; i < promptList.size();i++) {
            String userInput = promptList.get(i);
            GenerationResult result = callWithMessage(userInput);
            String result1 = result.getOutput().getChoices().get(0).getMessage().getContent();
//            System.out.println("-----------------输入------------------");
//            System.out.println(userInput);
//            System.out.println("------------------输出-----------------");
//            System.out.println(result1);
            //提取成为对象
            Map<String, List> stringListMap1 = extractTheQuestion(result1, singleQuestionNum * paperNum, 1, 1);
            List<SingleChoicesQuestion> singleChoicesQuestionsList = (List<SingleChoicesQuestion>)stringListMap1.get("singleChoicesQuestions");
            singleChoicesQuestions.addAll(singleChoicesQuestionsList);

            List<MultipleChoicesQuestion> multipleChoicesQuestionsList = (List<MultipleChoicesQuestion>)stringListMap1.get("MultipleChoicesQuestions");
            multipleChoicesQuestions.addAll(multipleChoicesQuestionsList);

            List<ShortAnswerQuestion> shortAnswerQuestionsList = (List<ShortAnswerQuestion>)stringListMap1.get("shortAnswerQuestions");
            shortAnswerQuestions.addAll(shortAnswerQuestionsList);

            List<FillBlankQuestion> fillBlankQuestionsList = (List<FillBlankQuestion>)stringListMap1.get("fillBlankQuestions");
            fillBlankQuestions.addAll(fillBlankQuestionsList);

            List<TorFQuestion> torFQuestionsList = (List<TorFQuestion>)stringListMap1.get("torFQuestions");
            torFQuestions.addAll(torFQuestionsList);

            List<CaseQuestion> caseQuestionsList = (List<CaseQuestion>)stringListMap1.get("caseQuestions");
            caseQuestions.addAll(caseQuestionsList);


        }

        if (paperNum>1) {
            List<List> singleChoicesLists = splitList(singleChoicesQuestions, singleQuestionNum);
            List<List> multipleChoicesLists = splitList(multipleChoicesQuestions, MultipleQuestionNum);
            List<List> shortAnswerLists = splitList(shortAnswerQuestions, shortQuestNum);
            List<List> fillBlankLists = splitList(fillBlankQuestions, fillBlankNum);
            List<List> torFLists = splitList(torFQuestions, torFNum);
            List<List> caseLists = splitList(caseQuestions, caseNum);

            if (singleChoicesLists.isEmpty()) {
                for (int i = 0; i < paperNum; i++) {
                    List list = new ArrayList<SingleChoicesQuestion>();
                    list.add(new SingleChoicesQuestion());
                    singleChoicesLists.add(list);
                }
            }
            if (multipleChoicesLists.isEmpty()) {
                List list = new ArrayList<MultipleChoicesQuestion>();
                list.add(new MultipleChoicesQuestion());
                for (int i = 0; i < paperNum; i++) {
                    multipleChoicesLists.add(list);
                }
            }
            if (shortAnswerLists.isEmpty()) {
                List list = new ArrayList<ShortAnswerQuestion>();
                list.add(new ShortAnswerQuestion());
                for (int i = 0; i < paperNum; i++) {
                    shortAnswerLists.add(list);
                }
            }
            if (fillBlankLists.isEmpty()) {
                List list = new ArrayList<FillBlankQuestion>();
                list.add(new FillBlankQuestion());
                for (int i = 0; i < paperNum; i++) {
                    fillBlankLists.add(list);
                }
            }
            if (torFLists.isEmpty()) {
                List list = new ArrayList<TorFQuestion>();
                list.add(new TorFQuestion());
                for (int i = 0; i < paperNum; i++) {
                    torFLists.add(list);
                }
            }
            if (caseLists.isEmpty()) {
                List list = new ArrayList<CaseQuestion>();
                list.add(new CaseQuestion());
                for (int i = 0; i < paperNum; i++) {
                    caseLists.add(list);
                }
            }

            for (int i = 0; i < paperNum; i++) {
                System.out.println("paperNum-->" + i);
                //TODO:文件名
                String wordFilePath2 = wordFilePath1 + System.currentTimeMillis() + i + ".docx";
                exportQuestionsToWord(multipleChoicesLists.get(i), singleChoicesLists.get(i), shortAnswerLists.get(i), fillBlankLists.get(i), torFLists.get(i), caseLists.get(i), wordFilePath2);
            }
            return "成功";
        }

        //4.写入word
        String fileName = wordFilePathLinx+name+".docx";
        exportQuestionsToWord(multipleChoicesQuestions, singleChoicesQuestions, shortAnswerQuestions, fillBlankQuestions, torFQuestions, caseQuestions, fileName);
        return fileName;
//        return "请重试";

    }

    /**
     * 分割list
     *
     * @param list
     * @param size
     * @return
     */
    private static List<List> splitList(List list, int size) {
        List<List> subLists = new ArrayList<>();
        for (int start = 0; start < list.size(); start += size) {
            int end = Math.min(start + size, list.size());
            subLists.add(new ArrayList<>(list.subList(start, end)));
        }
        return subLists;
    }


    /**
     * 调用api
     *
     * @param singleQuestionNum   单选题数量
     * @param MultipleQuestionNum 多题数量
     * @param shortQuestNum       简答题数量
     * @param difficultyStr       难度：0简单1中等2困难
     * @param text
     * @return
     * @throws Exception
     */
    private static GenerationResult callWithMessage(int singleQuestionNum, int MultipleQuestionNum, int shortQuestNum, int FillBlankNum, int torFNum, int caseNum, String difficultyStr, String text) throws Exception {

        Constants.apiKey = "sk-147806426fcc416f9aaba401c935c35d";

        Generation gen = new Generation();

        Message systemMsg = Message.builder()
                .role(Role.SYSTEM.getValue())
//                .content("You are a helpful assistant.")
                .content("You are an assistant who is good at solving questions.")
                .build();

        String directives1 ="请你根据文本，1.写出" + singleQuestionNum + "道单选题，" + MultipleQuestionNum + "道多选题，"
                + shortQuestNum + "道简答题，" + FillBlankNum + "道填空题，" + torFNum + "道判断题，" + caseNum + "道案例题，包括答案，解析。2.整体出题难度为" + difficultyStr +
                "3.选择题按照这个格式输出1. 题干？\\nA. 选项\\nB. 选项\\nC. 选项\\nD. 选项\\n**答案：答案**\\n**解析：**解析" +
                "4.简答题按照这个格式输出1. **题干**：题干？\\n**答案：**答案\\n**解析**：解析" +
                "5.填空题按照这个格式输出1. **题干**：题干？\\n**答案：**答案\\n**解析**：解析" +
                "6.判断题按照这个格式输出1. **题干**：题干？\\n**答案：**答案\\n**解析**：解析" +
                "7.案例题按照这个格式输出每个案例包含3个小题且要有案例内容 案例1\\n案例内容\\n1. **题干**：题干？\\n**答案：**答案\\n**解析**：解析" +
                "2. **题干**：题干？\\n**答案：**答案\\n**解析**：解析" +
                "3. **题干**：题干？\\n**答案：**答案\\n**解析**：解析" +
                "每个题型前加上###分隔，如###单选题，###多选题，###简答题，###填空题，###判断题，###案例题" +
                "严格按照以上格式输出，以下是文本" + text;

        Message userMsg = Message.builder()
                .role(Role.USER.getValue())
                .content(directives1)
                .build();

        GenerationParam param = GenerationParam.builder()
                .model("qwen-plus")
                .messages(Arrays.asList(systemMsg, userMsg))
                .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                .topP(0.8)
                .build();

        return gen.call(param);

    }

    private static GenerationResult callWithMessage(String prompt) throws Exception {

        Constants.apiKey = "sk-147806426fcc416f9aaba401c935c35d";

        Generation gen = new Generation();

        Message systemMsg = Message.builder()
                .role(Role.SYSTEM.getValue())
//                .content("You are a helpful assistant.")
                .content("You are an assistant who is good at solving questions.")
                .build();


        Message userMsg = Message.builder()
                .role(Role.USER.getValue())
                .content(prompt)
                .build();

        GenerationParam param = GenerationParam.builder()
                .model("qwen-plus")
                .messages(Arrays.asList(systemMsg, userMsg))
                .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                .topP(0.8)
                .build();

        return gen.call(param);

    }




    /**
     * 提取题目到对象
     *
     * @param content
     */
    private static Map<String, List> extractTheQuestion(String content, int singleQuestionNum, int MultipleQuestionNum, int shortQuestNum) throws Exception {
        Map<String, List> map = new HashMap<>();
        //1.单选题
        String[] questions1 = content.split("(?=###)");
        String singleQuestion = "";
        String regex = ".*###\\s*单选题.*";
        Pattern pattern = Pattern.compile(regex, Pattern.DOTALL);
        for (String question : questions1) {
            Matcher matcher = pattern.matcher(question);
            if (matcher.matches()) {
                singleQuestion = question;
            }
        }
//        singleQuestion = singleQuestion==null?questions1[0]:singleQuestion;

        //1.1单选题集合
        List<SingleChoicesQuestion> singleChoicesQuestions = new ArrayList<>();

        //1.2提取单选题
        String questionPattern = "(\\d+\\. .+?)(?=\\n\\s*\\-*\\s*[A-F]\\. )";
        String optionsPattern = "(\\s*\\-*\\s*[A-F]\\. .+?\\n)+";
        String answerPattern = "\\*\\*答案：\\**\\**(.*?)\\*\\*";
        String explanationPattern = "\\*\\*解析：\\**\\**(.+?)(?=(\\n\\d+\\. |\\n### |$))";

        Pattern qPattern = Pattern.compile(questionPattern, Pattern.DOTALL);
        Pattern oPattern = Pattern.compile(optionsPattern, Pattern.DOTALL);
        Pattern aPattern = Pattern.compile(answerPattern, Pattern.DOTALL);
        Pattern ePattern = Pattern.compile(explanationPattern, Pattern.DOTALL);

        Matcher qMatcher = qPattern.matcher(singleQuestion);
        Matcher aMatcher = aPattern.matcher(singleQuestion);
        Matcher eMatcher = ePattern.matcher(singleQuestion);

        int count = 1;
        while (qMatcher.find() && aMatcher.find() && eMatcher.find()) {
            SingleChoicesQuestion singleChoicesQuestion = new SingleChoicesQuestion();
            String question = qMatcher.group(1).trim();
            //1.2.1添加题目
            singleChoicesQuestion.setTopic(question);
            singleChoicesQuestion.setCount(count++);

            int optionsStart = qMatcher.end();
            int optionsEnd = singleQuestion.indexOf("**答案", optionsStart);
            if (optionsEnd == -1) optionsEnd = singleQuestion.length();
            String optionsText = singleQuestion.substring(optionsStart, optionsEnd).trim();
            Matcher singleOptionMatcher = Pattern.compile("\\s*\\-*\\s*([A-D]\\. .+?)(?=\\n|\\Z)").matcher(optionsText);
            StringBuilder singleOptionText = new StringBuilder();
            while (singleOptionMatcher.find()) {
                singleOptionText.append(singleOptionMatcher.group(1).trim()).append("-");
            }
            //1.2.2添加选项
            String[] parts = singleOptionText.toString().split("-");
            for (int i = 0; i < parts.length; i++) {
                if (parts[i].length() < 2) {
                    continue;
                }
                if (parts[i].startsWith("A")) {
                    singleChoicesQuestion.setOptionA(parts[i].substring(2).trim());// 选项A
                } else if (parts[i].startsWith("B")) {
                    singleChoicesQuestion.setOptionB(parts[i].substring(2).trim());// 选项B
                } else if (parts[i].startsWith("C")) {
                    singleChoicesQuestion.setOptionC(parts[i].substring(2).trim());// 选项C
                } else if (parts[i].startsWith("D")) {
                    singleChoicesQuestion.setOptionD(parts[i].substring(2).trim());// 选项D
                }

            }

            //1.2.3添加答案
            String answer = aMatcher.group(1).trim();
            singleChoicesQuestion.setAnswer(answer);
            //1.2.3添加解析
            String explanation = eMatcher.group(1).trim();
            singleChoicesQuestion.setParse(explanation);

            singleChoicesQuestions.add(singleChoicesQuestion);

        }

        //2.多选题
        String[] questions2 = content.split("(?=### 多选题)");
        String multipleQuestion = "";
        String multipleRegex = ".*###\\s*多选题.*";
        Pattern multipPattern = Pattern.compile(multipleRegex, Pattern.DOTALL);
        for (String question : questions1) {
            Matcher matcher = multipPattern.matcher(question);
            if (matcher.matches()) {
                multipleQuestion = question;
            }
        }
//        multipleQuestion = multipleQuestion==null?questions1[1]:multipleQuestion;

        //2.1多选题集合
        List<MultipleChoicesQuestion> MultipleChoicesQuestions = new ArrayList<>();

        Matcher qMatcher1 = qPattern.matcher(multipleQuestion);
        Matcher aMatcher1 = aPattern.matcher(multipleQuestion);
        Matcher eMatcher1 = ePattern.matcher(multipleQuestion);

        int count1 = 1;
        while (qMatcher1.find() && aMatcher1.find() && eMatcher1.find()) {
            MultipleChoicesQuestion multipleChoicesQuestion = new MultipleChoicesQuestion();
            String question = qMatcher1.group(1).trim();
            //2.2.1添加题目
            multipleChoicesQuestion.setTopic(question);
            multipleChoicesQuestion.setCount(count1++);

            int optionsStart = qMatcher1.end();
            int optionsEnd = multipleQuestion.indexOf("**答案", optionsStart);
            if (optionsEnd == -1) optionsEnd = multipleQuestion.length();
            String optionsText = multipleQuestion.substring(optionsStart, optionsEnd).trim();
            Matcher singleOptionMatcher = Pattern.compile("\\s*\\-*\\s*([A-F]\\. .+?)(?=\\n|\\Z)").matcher(optionsText);
            StringBuilder singleOptionText = new StringBuilder();
            while (singleOptionMatcher.find()) {
                singleOptionText.append(singleOptionMatcher.group(1).trim()).append("-");
            }
            //2.2.2添加选项
            String[] parts = singleOptionText.toString().split("-");
            for (int i = 0; i < parts.length; i++) {
                if (parts[i].length() < 2) {
                    continue;
                }
                if (parts[i].startsWith("A")) {
                    multipleChoicesQuestion.setOptionA(parts[i].substring(2).trim());// 选项A
                } else if (parts[i].startsWith("B")) {
                    multipleChoicesQuestion.setOptionB(parts[i].substring(2).trim());// 选项B
                } else if (parts[i].startsWith("C")) {
                    multipleChoicesQuestion.setOptionC(parts[i].substring(2).trim());// 选项C
                } else if (parts[i].startsWith("D")) {
                    multipleChoicesQuestion.setOptionD(parts[i].substring(2).trim());// 选项D
                } else if (parts[i].startsWith("E")) {
                    multipleChoicesQuestion.setOptionE(parts[i].substring(2).trim());// 选项E
                } else if (parts[i].startsWith("F")) {
                    multipleChoicesQuestion.setOptionF(parts[i].substring(2).trim());// 选项F
                }


            }

            //2.2.3添加答案
            String answer = aMatcher1.group(1).trim();
            multipleChoicesQuestion.setAnswer(answer);
            //2.2.3添加解析
            String explanation = eMatcher1.group(1).trim();
            multipleChoicesQuestion.setParse(explanation);

            MultipleChoicesQuestions.add(multipleChoicesQuestion);

        }


        //3.简答题
        String[] questions3 = content.split("(?=### 简答题)");
        String shortAnswerQuestion = "";
        String shortAnswerRegex = ".*###\\s*简答题.*";
        Pattern shortAnswerPattern = Pattern.compile(shortAnswerRegex, Pattern.DOTALL);
        for (String question : questions1) {
            Matcher matcher = shortAnswerPattern.matcher(question);
            if (matcher.matches()) {
                shortAnswerQuestion = question;
            }
        }
//        shortAnswerQuestion = shortAnswerQuestion==null?questions1[2]:shortAnswerQuestion;


        List<ShortAnswerQuestion> shortAnswerQuestions = new ArrayList<>();

        //3.1提取
        String shortAnswerQuestionPattern = "(\\d+\\. .+?)(?=\\n\\s*\\*\\*答案)";
        String shortAnswerAnswerPattern = "\\*\\*答案：*\\*\\*(.*?)\\n\\s*\\*\\*";
        String shortAnswerExplanationPattern = "\\*\\*解析\\*\\*(.+?)(?=(\\n\\d+\\. |\\n### |$))";

        Pattern qShortAnswerPattern = Pattern.compile(shortAnswerQuestionPattern, Pattern.DOTALL);
        Pattern aShortAnswerPattern = Pattern.compile(shortAnswerAnswerPattern, Pattern.DOTALL);
        Pattern eShortAnswerPattern = Pattern.compile(shortAnswerExplanationPattern, Pattern.DOTALL);

        Matcher qshortAnswerMatcher = qShortAnswerPattern.matcher(shortAnswerQuestion);
        Matcher ashortAnswerMatcher = aShortAnswerPattern.matcher(shortAnswerQuestion);
        Matcher eshortAnswerMatcher = eShortAnswerPattern.matcher(shortAnswerQuestion);

        int count2 = 1;
        while (qshortAnswerMatcher.find() && ashortAnswerMatcher.find() && eshortAnswerMatcher.find()) {
            ShortAnswerQuestion shortAnswerQuestion1 = new ShortAnswerQuestion();
            String question = qshortAnswerMatcher.group(1).trim();
            //3.2.1添加题目
            shortAnswerQuestion1.setTopic(question);
            shortAnswerQuestion1.setCount(count2++);

            //3.2.2添加选项

            //3.2.3添加答案
            String answer = ashortAnswerMatcher.group(1).trim();
            shortAnswerQuestion1.setAnswer(answer);
            //3.2.3添加解析
            if (eshortAnswerMatcher.find()) {
                String explanation = eshortAnswerMatcher.group(1).trim();
                shortAnswerQuestion1.setParse(explanation);
            }

            shortAnswerQuestions.add(shortAnswerQuestion1);
        }

        //如果提取不全重新来一遍
        if (shortAnswerQuestions.size() != shortQuestNum) {
            //清空
            shortAnswerQuestions.clear();
            //3.1提取
            String shortAnswerAnswerPattern2 = "^(\\d+)\\s*(.*)(答案：*.*?\\*\\*\\*)";
            String[] questions = shortAnswerQuestion.split("(?=\\d\\s*\\.)");


            Pattern aShortAnswerPattern2 = Pattern.compile(shortAnswerAnswerPattern2, Pattern.DOTALL);
            for (String q : questions) {
                q = q + "***";
                Matcher ashortAnswerMatcher2 = aShortAnswerPattern2.matcher(q);

                int count3 = 1;
                while (ashortAnswerMatcher2.find()) {
                    String trim1 = ashortAnswerMatcher2.group(1).trim();
                    String trim = ashortAnswerMatcher2.group(2).trim();
                    String trim2 = ashortAnswerMatcher2.group(3).trim().substring(3);

                    ShortAnswerQuestion shortAnswerQuestion1 = new ShortAnswerQuestion();
                    String question = trim1 + trim;
                    //3.2.1添加题目
                    shortAnswerQuestion1.setTopic(question);
                    shortAnswerQuestion1.setCount(count3++);

                    //3.2.3添加答案
                    String answer = trim2;
                    shortAnswerQuestion1.setAnswer(answer);

                    shortAnswerQuestions.add(shortAnswerQuestion1);
                }

            }


        }

        //4.填空题
        String fillBlankQuestion = "";
        String fillBlankRegex = ".*###\\s*填空题.*";
        Pattern fillBlankPattern = Pattern.compile(fillBlankRegex, Pattern.DOTALL);
        for (String question : questions1) {
            Matcher matcher = fillBlankPattern.matcher(question);
            if (matcher.matches()) {
                fillBlankQuestion = question;
            }
        }


        List<FillBlankQuestion> fillBlankQuestions = new ArrayList<>();

        //3.1提取
        //3.1提取
        String shortAnswerAnswerPattern2 = "^(\\d+)\\s*(.*)(答案：*.*?\\*\\*\\*)";
        String[] questions = fillBlankQuestion.split("(?=\\d\\s*\\.)");

        Pattern aShortAnswerPattern2 = Pattern.compile(shortAnswerAnswerPattern2, Pattern.DOTALL);
        for (String q : questions) {
            q = q + "***";
            Matcher ashortAnswerMatcher2 = aShortAnswerPattern2.matcher(q);

            int count3 = 1;
            while (ashortAnswerMatcher2.find()) {
                String trim1 = ashortAnswerMatcher2.group(1).trim();
                String trim = ashortAnswerMatcher2.group(2).trim();
                String trim2 = ashortAnswerMatcher2.group(3).trim().substring(3);

                FillBlankQuestion fillBlankQuestion1 = new FillBlankQuestion();
                String question = trim1 + trim;
                //3.2.1添加题目
                fillBlankQuestion1.setTopic(question);
                fillBlankQuestion1.setCount(count3++);

                //3.2.3添加答案
                String answer = trim2;
                fillBlankQuestion1.setAnswer(answer);

                fillBlankQuestions.add(fillBlankQuestion1);
            }

        }

        //4.判断题
        String torFQuestion = "";
        String torFRegex = ".*###\\s*判断题.*";
        Pattern torFPattern = Pattern.compile(torFRegex, Pattern.DOTALL);
        for (String question : questions1) {
            Matcher matcher = torFPattern.matcher(question);
            if (matcher.matches()) {
                torFQuestion = question;
            }
        }
//        torFQuestion = torFQuestion==null?questions1[4]:torFQuestion;

        List<TorFQuestion> torFQuestions = new ArrayList<>();
        String[] questions4 = torFQuestion.split("(?=\\d\\s*\\.)");

        for (String q : questions4) {
            q = q + "***";
            Matcher ashortAnswerMatcher2 = aShortAnswerPattern2.matcher(q);

            int count3 = 1;
            while (ashortAnswerMatcher2.find()) {
                String trim1 = ashortAnswerMatcher2.group(1).trim();
                String trim = ashortAnswerMatcher2.group(2).trim();
                String trim2 = ashortAnswerMatcher2.group(3).trim().substring(3);

                TorFQuestion torFQuestion1 = new TorFQuestion();
                String question = trim1 + trim;
                //3.2.1添加题目
                torFQuestion1.setTopic(question);
                torFQuestion1.setCount(count3++);

                //3.2.3添加答案
                String answer = trim2;
                torFQuestion1.setAnswer(answer);

                torFQuestions.add(torFQuestion1);
            }

        }

        //4.案例题
        String caseQuestion = "";
        String caseRegex = ".*###\\s*案例题.*";
        Pattern casePattern = Pattern.compile(caseRegex, Pattern.DOTALL);
        for (String question : questions1) {
            Matcher matcher = casePattern.matcher(question);
            if (matcher.matches()) {
                caseQuestion = question;
            }
        }

        List<CaseQuestion> caseQuestions = new ArrayList<>();

        String[] questions5 = caseQuestion.split("(?=案例\\d)");
        String caseAnswerPattern2 = "^(\\d+)\\s*(.*)(答案：*.*?\\*\\*\\*)";
        Pattern casePattern2 = Pattern.compile(caseAnswerPattern2, Pattern.DOTALL);


        int count4 = 0;
        for (String q : questions5) {
            if (count4 == 0) {
                count4++;
                continue;
            }
            String[] question3 = q.split("(?=\\b\\d\\s*\\.)");
            CaseQuestion caseQuestion1 = new CaseQuestion();
            caseQuestion1.setCaseTopic(question3[0]);
            List<ShortAnswerQuestion> shortAnswerQuestionList = new ArrayList<>();
            for (String s : question3) {
                s = s + "***";
                Matcher caseMatcher2 = casePattern2.matcher(s);


                int count3 = 1;
                while (caseMatcher2.find()) {
                    String trim1 = caseMatcher2.group(1).trim();
                    String trim = caseMatcher2.group(2).trim();
                    String trim2 = caseMatcher2.group(3).trim().substring(3);

                    ShortAnswerQuestion shortAnswerQuestion1 = new ShortAnswerQuestion();
                    String question = trim1 + trim;
                    //3.2.1添加题目
                    shortAnswerQuestion1.setTopic(question);
                    shortAnswerQuestion1.setCount(count3++);

                    //3.2.3添加答案
                    String answer = trim2;
                    shortAnswerQuestion1.setAnswer(answer);

                    shortAnswerQuestionList.add(shortAnswerQuestion1);
                }
            }
            caseQuestion1.setShortAnswerQuestionList(shortAnswerQuestionList);
            caseQuestions.add(caseQuestion1);


        }


        //4.写入word
        map.put("MultipleChoicesQuestions", MultipleChoicesQuestions);
        map.put("singleChoicesQuestions", singleChoicesQuestions);
        map.put("shortAnswerQuestions", shortAnswerQuestions);
        map.put("fillBlankQuestions", fillBlankQuestions);
        map.put("torFQuestions", torFQuestions);
        map.put("caseQuestions", caseQuestions);
//        exportQuestionsToWord(MultipleChoicesQuestions,singleChoicesQuestions,shortAnswerQuestions,wordFilePath);
        return map;
    }

    /**
     * 将3种题型写入word
     *
     * @param questions
     * @param questions1
     * @param questions2
     * @param filePath
     */
    private static void exportQuestionsToWord(List<MultipleChoicesQuestion> questions,
                                              List<SingleChoicesQuestion> questions1,
                                              List<ShortAnswerQuestion> questions2,
                                              List<FillBlankQuestion> questions3,
                                              List<TorFQuestion> questions4,
                                              List<CaseQuestion> questions5,
                                              String filePath) {
        XWPFDocument document = new XWPFDocument();

        //1.单选题
        int isSigleCount = 0;
        for (SingleChoicesQuestion question : questions1) {
            if (question==null) {
                break;
            }
            XWPFParagraph paragraph = document.createParagraph();
            if (isSigleCount == 0) {
                isSigleCount++;
                XWPFRun runCount = paragraph.createRun();
                runCount.setText("单选题");
                runCount.setBold(true);
            }
            // 序号
            XWPFRun runCount = paragraph.createRun();
//            runCount.setText(question.getCount() + ". ");
            runCount.setBold(true);

            // 题干
            XWPFRun runTopic = paragraph.createRun();
            runTopic.setText(question.getTopic());

            // 选项
            String[] options = {question.getOptionA(), question.getOptionB(),
                    question.getOptionC(), question.getOptionD(),
                    question.getOptionE(), question.getOptionF()};
            for (int i = 0; i < options.length; i++) {
                if (options[i] != null && !options[i].isEmpty()) {
                    paragraph = document.createParagraph();
                    XWPFRun runOption = paragraph.createRun();
                    runOption.setText((char) ('A' + i) + ") " + options[i]);
                }
            }

            // 添加空行
//            document.createParagraph();

            // 答案
            paragraph = document.createParagraph();
            XWPFRun runAnswer = paragraph.createRun();
            runAnswer.setText("答案: " + question.getAnswer());

            // 添加空行
//            document.createParagraph();

            // 解析
            if (question.getParse() != null && !question.getParse().isEmpty()) {
                paragraph = document.createParagraph();
                XWPFRun runParse = paragraph.createRun();
                runParse.setText("解析: " + question.getParse());
            }

            // 添加空行
            document.createParagraph();
        }

        //2.多选题
        int isMultipleCount = 0;
        for (MultipleChoicesQuestion question : questions) {
            if (question==null) {
                break;
            }
            XWPFParagraph paragraph = document.createParagraph();
            if (isMultipleCount == 0) {
                isMultipleCount++;
                XWPFRun runCount = paragraph.createRun();
                runCount.setText("多选题");
                runCount.setBold(true);
            }
            // 序号
//            paragraph.createRun().setText(question.getCount() + ". ");
            paragraph.createRun().setText(question.getTopic());

            // 选项
            String[] options = {question.getOptionA(), question.getOptionB(),
                    question.getOptionC(), question.getOptionD(),
                    question.getOptionE(), question.getOptionF()};
            for (int i = 0; i < options.length; i++) {
                if (options[i] != null && !options[i].isEmpty()) {
                    paragraph = document.createParagraph();
                    paragraph.createRun().setText((char) ('A' + i) + ") " + options[i]);
                }
            }

            // 答案
            paragraph = document.createParagraph();
            paragraph.createRun().setText("答案: " + question.getAnswer());

            // 解析
            if (question.getParse() != null && !question.getParse().isEmpty()) {
                paragraph = document.createParagraph();
                paragraph.createRun().setText("解析: " + question.getParse());
            }

            // 添加空行
            document.createParagraph();
        }

        //4.填空题
        int isFillCount = 0;
        for (FillBlankQuestion question : questions3) {
            if (question==null) {
                break;
            }
            XWPFParagraph paragraph = document.createParagraph();
            if (isFillCount == 0) {
                isFillCount++;
                XWPFRun runCount = paragraph.createRun();
                runCount.setText("填空题");
                runCount.setBold(true);
            }
            // 序号
            XWPFRun runCount = paragraph.createRun();
//            runCount.setText(question.getCount() + ". ");
            runCount.setBold(true);

            // 题干
            XWPFRun runTopic = paragraph.createRun();
            runTopic.setText(question.getTopic());

            // 添加空行
//            document.createParagraph();

            // 答案
            paragraph = document.createParagraph();
            XWPFRun runAnswer = paragraph.createRun();
            runAnswer.setText("答案: " + question.getAnswer());

            // 添加空行
//            document.createParagraph();

            // 解析
            if (question.getParse() != null && !question.getParse().isEmpty()) {
                paragraph = document.createParagraph();
                XWPFRun runParse = paragraph.createRun();
                runParse.setText("解析: " + question.getParse());
            }

            // 添加空行
            document.createParagraph();
        }

        //5.判断题
        int isTorFCount = 0;
        for (TorFQuestion question : questions4) {
            if (question==null) {
                break;
            }
            XWPFParagraph paragraph = document.createParagraph();
            if (isTorFCount == 0) {
                isTorFCount++;
                XWPFRun runCount = paragraph.createRun();
                runCount.setText("判断题");
                runCount.setBold(true);
            }
            // 序号
            XWPFRun runCount = paragraph.createRun();
//            runCount.setText(question.getCount() + ". ");
            runCount.setBold(true);

            // 题干
            XWPFRun runTopic = paragraph.createRun();
            runTopic.setText(question.getTopic());

            // 添加空行
//            document.createParagraph();

            // 答案
            paragraph = document.createParagraph();
            XWPFRun runAnswer = paragraph.createRun();
            runAnswer.setText("答案: " + question.getAnswer());

            // 添加空行
//            document.createParagraph();

            // 解析
            if (question.getParse() != null && !question.getParse().isEmpty()) {
                paragraph = document.createParagraph();
                XWPFRun runParse = paragraph.createRun();
                runParse.setText("解析: " + question.getParse());
            }

            // 添加空行
            document.createParagraph();
        }

        //3.简答题
        int isShortAnswer = 0;
        for (ShortAnswerQuestion question : questions2) {
            if (question==null) {
                break;
            }
            XWPFParagraph paragraph = document.createParagraph();
            if (isShortAnswer == 0) {
                isShortAnswer++;
                XWPFRun runCount = paragraph.createRun();
                runCount.setText("简答题");
                runCount.setBold(true);
            }

            // 序号
            XWPFRun runCount = paragraph.createRun();
//            runCount.setText(question.getCount() + ". ");
            runCount.setBold(true);

            // 题干
            XWPFRun runTopic = paragraph.createRun();
            runTopic.setText(question.getTopic());

            // 添加空行
//            document.createParagraph();

            // 答案
            paragraph = document.createParagraph();
            XWPFRun runAnswer = paragraph.createRun();
            runAnswer.setText("答案: " + question.getAnswer());

            // 添加空行
//            document.createParagraph();

            // 解析
            if (question.getParse() != null && !question.getParse().isEmpty()) {
                paragraph = document.createParagraph();
                XWPFRun runParse = paragraph.createRun();
                runParse.setText("解析: " + question.getParse());
            }

            // 添加空行
            document.createParagraph();
        }

        //5.案例题
        int isCaseCount = 0;
        for (CaseQuestion question : questions5) {
            if (question==null||question.getShortAnswerQuestionList()==null) {
                break;
            }
            XWPFParagraph paragraph = document.createParagraph();

            if (isCaseCount == 0) {
                isCaseCount++;
                XWPFRun runCount = paragraph.createRun();
                runCount.setText("案例题");
                runCount.setBold(true);
            }


            // 题干
            XWPFRun runTopic = paragraph.createRun();
            runTopic.setText(question.getCaseTopic());
            document.createParagraph();
            for (ShortAnswerQuestion shortAnswerQuestion : question.getShortAnswerQuestionList()) {
                if (shortAnswerQuestion==null) {
                    break;
                }
                XWPFRun runTopic1 = paragraph.createRun();
                runTopic1.setText(shortAnswerQuestion.getTopic());
                paragraph = document.createParagraph();
                XWPFRun runAnswer = paragraph.createRun();
                runAnswer.setText("答案: " + shortAnswerQuestion.getAnswer());
                // 解析
                if (shortAnswerQuestion.getParse() != null && !shortAnswerQuestion.getParse().isEmpty()) {
                    paragraph = document.createParagraph();
                    XWPFRun runParse = paragraph.createRun();
                    runParse.setText("解析: " + shortAnswerQuestion.getParse());
                }
                document.createParagraph();
            }


            // 添加空行
            document.createParagraph();
        }


        try (FileOutputStream out = new FileOutputStream(filePath)) {
            document.write(out);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                document.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    /**
     * 转换为列表
     * @return
     */
    public static List<String> convertList(int singleQuestionNum,
                                           int MultipleQuestionNum,
                                           int shortQuestNum,
                                           int FillBlankNum,
                                           int torFNum,
                                           int caseNum, int difficulty, int paperNum,
                                           String text){
        String difficultyStr = difficulty == 0 ? "简单" : difficulty == 1 ? "中等" : difficulty == 2 ? "困难" : "中等";

        String singleQuestionPrompt="请你根据文本，1.写出" + singleQuestionNum * paperNum + "道单选题2.整体出题难度为" + difficultyStr +"3.选择题按照这个格式输出1. 题干？\\nA. 选项\\nB. 选项\\nC. 选项\\nD. 选项\\n**答案：答案**\\n**解析：**解析。";
        String multipleQuestionPrompt="请你根据文本，1.写出"+ MultipleQuestionNum * paperNum + "道多选题，2.整体出题难度为" + difficultyStr +"3.选择题按照这个格式输出1. 题干？\\nA. 选项\\nB. 选项\\nC. 选项\\nD. 选项\\n**答案：答案**\\n**解析：**解析。";
        String shortQuestPrompt="请你根据文本，1.写出" + shortQuestNum* paperNum  + "道简答题，2.整体出题难度为" + difficultyStr +"，简答题按照这个格式输出1. **题干**：题干？\\n**答案：**答案\\n**解析**：解析。";
        String fillBlankPrompt="请你根据文本，1.写出" + FillBlankNum* paperNum  + "道填空题，2.整体出题难度为" + difficultyStr +"，填空题按照这个格式输出1. **题干**：题干？\\n**答案：**答案\\n**解析**：解析。";
        String torFPrompt="请你根据文本，1.写出" + torFNum * paperNum + "道判断题，2.整体出题难度为" + difficultyStr +"，判断题按照这个格式输出1. **题干**：题干？\\n**答案：**答案\\n**解析**：解析。";
        String casePrompt="请你根据文本，写出" + caseNum * paperNum + "道案例题，整体出题难度为" + difficultyStr +"，案例题按照这个格式输出每个案例包含3个小题且要有案例内容 案例1\\n案例内容\\n1. **题干**：题干？\\n**答案：**答案\\n**解析**：解析";
        String endStr = "每个题型前加上###分隔，如###单选题，###多选题，###简答题，###填空题，###判断题，###案例题";
        String textStr = "严格按照以上格式输出，以下是文本" + text;

        List<String> list = new ArrayList<>();
        if (singleQuestionNum!=0) {
            list.add(singleQuestionPrompt);
        }
        if (MultipleQuestionNum!=0) {
            list.add(multipleQuestionPrompt);
        }
        if (shortQuestNum!=0) {
            list.add(shortQuestPrompt);
        }
        if (FillBlankNum!=0) {
            list.add(fillBlankPrompt);
        }
        if (torFNum!=0) {
            list.add(torFPrompt);
        }
        if (caseNum!=0) {
            list.add(casePrompt);
        }

        for (int i = 0; i < list.size(); i++) {
            String s = list.get(i) + endStr + textStr;
            list.set(i,s);
        }
        return list;
    }


}
